<?php

/*
 * Camelot PHP Tools
 *
 * @version 2.0
 * @author Bendsoft
 * @package PHP Tools
 * @subpackage Camelot
 * @license FreeBSD License (www.bendsoft.com/licensing/)
 *
 */

/**
 * Builds a Document library browser
 * 
 * @author Bendsoft
 */
class SharePointDocLibHelper {

    public $ConnectionName;
    public $DocumentLibraryName;
    public $DocumentLibraries;
    public $DefaultLibrary;
    public $ShowUploadControls = true;
    public $ShowNewFolderControl = true;
    public $DocumentTree;
    public $TreeParentId;
    public $RootLevel;
    public $_createFolder = false;
    public $_parentId;
    private $session;

    public function __construct($args = null) {
        /**
         * Handled arguments
         * - connectionName
         * - documentLibrary
         * - defaultLibrary (index or name)
         * - showNewFolderControl
         * - showUploadControls
         */
        // Show new folder controls, or not
        if ($this->getIfSet($args, 'showNewFolderControl')) {
            $this->ShowNewFolderControl = $args['showNewFolderControl'];
        }

        // Show upload controls, or not
        if ($this->getIfSet($args, 'showUploadControls')) {
            $this->ShowUploadControls = $args['showUploadControls'];
        }

        // Check if connectionName is set, if not we terminate the class
        if ($this->getIfSet($args, 'connectionName')) {
            $this->ConnectionName = $args['connectionName'];
        } else {
            echo "No connection stated in the SharePointDocLib argument array";
            unset($this);
            return;
        }

        // Check if defaultLibrary is set
        if ($this->getIfSet($args, 'defaultLibrary')) {
            $this->DefaultLibrary = $args['defaultLibrary'];
        }

        // construct session object
        $this->session = new SharePointDocLibHelperSessions();

        // Set the document library to fetch
        $this->setDocumentLibrary();

        // Set the parent id, if any
        $this->_parentId = $this->setParentId();

        /**
         * ACTIONS AND POSTS
         */
        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case 'reload':
                    $this->session->ClearDocLib();
                    header('Location: ' . $_SERVER["SCRIPT_NAME"]);
                    die;
                    break;
                case 'createfolder':
                    $this->_createFolder = true;
                    break;
            }
        }

        // If a download is requested
        if (isset($_GET["download"]))
            $this->downloadFile($_GET["download"]);

        // Creating folders
        if (isset($_POST["txtNewFolder"]) && $_POST["txtNewFolder"] != "") {
            $this->createFolder($_POST["txtNewFolder"]);
        }


        // Uploading a file
        if (isset($_FILES["file"]) && $_FILES["file"]["name"] != "") {
            if ($this->session->GetDocLib() == "")
                $this->session->SetDocLib($this->getCurrentDocumentLibraryData());

            $this->uploadFile();
        }
        /**
         * GET AND RENDERING OF DATA
         */
        // Before rendering we must ensure we're not living in a in a POST
        if (isset($_POST['submit']) || $_POST) {
            $this->redirectToUrl();
            return;
            //die;
        }

        // Fetch requested document library
        $this->session->SetDocLib($this->getCurrentDocumentLibraryData());

        // Get all document libraries
        if ($this->getIfSet($args, 'documentLibrary')) {
            $this->DocumentLibraries = $this->getDocumentLibraries($args['documentLibrary']);
        } else {
            //$this->setDocumentLibrary();
            $this->DocumentLibraries = $this->getDocumentLibraries();
        }

        // Build some rendering dependencies
        $this->DocumentTree = new DocumentTree($this->session->GetDocLib(), $this->_parentId);
        $this->DocumentTree->buildtree();

        // Find the parentId of the current loaded folder
        $this->TreeParentId = (isset($this->session->GetDocLib()->foldersParentID[$this->_parentId])) ? $this->session->GetDocLib()->foldersParentID[$this->_parentId] : 0;
        $this->RootLevel = ($this->_parentId > 0) ? true : false;

        // Render the page
        $this->renderPage();
    }

    private function redirectToUrl($includeQuerystring = true) {
        if ($includeQuerystring == true) {
            $parentQuerystring = ($this->setParentId() > 0) ? "parentId=" . $this->setParentId() : "";
        } else {
            $parentQuerystring = "";
        }
        $url = (strpos($_SERVER["REQUEST_URI"], "?") !== true) ? $_SERVER["REQUEST_URI"] : $_SERVER["REQUEST_URI"] . "?";

        // Use the header redirect if you like it, we don't
        //header('Location: ' . $url . $parentQuerystring);
        echo "<script>location.href='$url$parentQuerystring'</script>";
    }

    private function setParentId() {
        if (isset($_GET["parentId"])) {
            return $_GET["parentId"];
        }

        if (isset($_POST["parentId"])) {
            return $_POST["parentId"];
        }

        return 0;
    }

    private function setDocumentLibrary($documentLibrary = null) {

        $a = ";";

        if (isset($_POST['﻿ddlSiteDocLibs']) && $_POST['﻿ddlSiteDocLibs'] != "" && $this->session->GetDocumentLibrary() != $_POST['﻿ddlSiteDocLibs']) {
            $this->session->SetDocumentLibrary($_POST['﻿ddlSiteDocLibs']);
            $this->DocumentLibraryName = $this->session->GetDocumentLibrary();
            $this->clearSessionCache();
            $this->redirectToUrl(false);
        } else {
            if ($this->session->GetDocumentLibrary() != "") {
                $this->DocumentLibraryName = $this->session->GetDocumentLibrary();
            }
        }

        // If nothing is set, check for a default library
        if (!isset($this->DocumentLibraryName)) {
            $this->DocumentLibraryName = $this->DefaultLibrary;
        }
    }

    private function getCurrentDocumentLibraryData() {
        // If the sessions are good and we haven't changed the document libraries we can return the data in the session
        if ($this->session->GetDocLib() != "" &&
                $this->session->GetDocumentLibrary() != "" &&
                (isset($this->DocumentLibraryName) && $this->session->GetDocumentLibrary() == $this->DocumentLibraryName) &&
                $this->DocumentLibraryName == $this->session->GetDocLib()->documentLibrary) {
            return $this->session->GetDocLib();
        }

        if (!isset($this->DocumentLibraryName) || $this->DocumentLibraryName == "") {
            return null;
        }

        try {
            // Get one library and it's contents
            $do = new SharePointDocumentLibrary($this->ConnectionName, $this->DocumentLibraryName);

            return $do;
        } catch (Exception $exc) {
            echo "<h2>Could not fetch document library</h2><ul><ol>Did you set up settings.php?</ol><ol>Check your SQL syntax</ol><ol>Check the rest of your argument array</ol></ul>";
            echo $exc->getTraceAsString();
            return null;
        }
    }

    private function getDocumentLibraries($documentLibrary = null) {
        if (!is_null($documentLibrary)) {
            $documentLibraries = explode(constant("DELIMITER"), $documentLibrary);

            $arrayobj = new ArrayObject();

            foreach ($documentLibraries as $library) {
                if (trim($library) != "")
                    $arrayobj->append(new CamelotDocumentLibrariesObject(trim($library), trim($library), false, 1, -1, trim($library)));
            }

            return (array) $arrayobj;
        }

        try {
            $sharePointDocumentLibraries = new SharePointDocumentLibraries($this->ConnectionName);
            $sharePointDocumentLibraries = (array) $sharePointDocumentLibraries->CamelotDocumentLibrariesObjects;
            $childRows = array_filter($sharePointDocumentLibraries, array($this, 'filterByHidden'));
            return $childRows;
        } catch (Exception $exc) {
            echo "<h2>Could not fetch document libraries</h2><ul><ol>Did you set up settings.php?</ol><ol>Check your SQL syntax</ol><ol>Check the rest of your argument array</ol></ul>";
            echo $exc->getTraceAsString();
            return null;
        }
    }

    private function filterByHidden($array) {
        return ($array->hidden == "false");
    }

    private function downloadFile($file) {
        try {
            $command = new DownloadCommand();
            $command->connection_name = $this->ConnectionName;
            $command->listName = $this->DocumentLibraryName;
            $command->file = $file;

            $result = new SharePointProcedure($command);
        } catch (CamelotException $exc) {
            echo "<script>alert('$exc->message');</script>";
        }
    }

    private function createFolder($folderName) {

        if (!isset($folderName) || $folderName == "") {
            return;
        }

        try {
            $parentFolder = $this->getParentFolderPath();

            $command = new CreateFolderCommand();
            $command->connection_name = $this->ConnectionName;
            $command->listName = $this->DocumentLibraryName;
            $command->folder = $parentFolder . $folderName;

            $result = new SharePointProcedure($command);

            $this->clearSessionCache();
        } catch (CamelotException $exc) {
            echo "<script>alert('$exc->message');</script>";
        }
    }

    private function uploadFile() {
        $parentFolder = $this->getParentFolderPath();

        try {
            $command = new UploadCommand();
            $command->connection_name = $this->ConnectionName;
            $command->data = $_FILES;
            $command->folder = $parentFolder;
            $command->listName = $this->DocumentLibraryName;

            // Execute command
            $result = new SharePointProcedure($command);

            // All good
            $this->clearSessionCache();
        } catch (CamelotException $exc) {
            echo "<script>alert('$exc->message');</script>";
        }
    }

    private function getParentFolderPath() {
        if ($this->session->GetDocLib() != "" && $this->_parentId > 0) {
            return $this->session->GetDocLib()->folders[$this->_parentId] . "/";
        }
        return "";
    }

    private function clearSessionCache($force = null) {

        if (isset($force)) {
            $this->session = null;
        } else {
            $this->session->ClearDocLib(); // clear the doclib session
        }

        // set session to renew cache file if wsdl_cache is enabled
        $_SESSION['forceRenewCache'] = true;
    }

    private function renderPage() {

        // Render twig
        require_once '../twig/lib/Twig/Autoloader.php';
        Twig_Autoloader::register();
        $loader = new Twig_Loader_Filesystem('../templates');
        $twig = new Twig_Environment($loader);
        $template = $twig->loadTemplate('documentlibrary.html');
        echo $template->render(array(
            'files_folders' => $this->DocumentTree->DocumentTreeObject,
            'root_level' => $this->RootLevel,
            'document_libraries' => $this->DocumentLibraries,
            'document_library_name' => $this->DocumentLibraryName,
            'create_folder' => $this->_createFolder,
            'create_folder_url' => isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] . "&action=createfolder" : "" . "action=createfolder",
            'parent_id' => $this->_parentId,
            'tree_parent_id' => $this->TreeParentId,
            'show_upload_controls' => $this->ShowUploadControls,
            'show_new_folder_control' => $this->ShowNewFolderControl
        ));
    }

    private function getIfSet($args, $param) {
        if (isset($args[$param]) && $args[$param] != "")
            return true;

        if (isset($args[$param]) && is_bool($args[$param]))
            return true;

        return false;
    }

}

?>
